/**
 * 历史记录管理服务
 * 用于管理GenerationItem的历史记录和动态属性
 */

export interface GenerationHistoryItem {
  id: string;
  date: string;
  imageUrls: string[]; // 改为数组支持多张图片（用于显示）
  lightccImageUrls: string[]; // LightCC返回的图片URL（用于API调用）
  format: string;
  aspectRatio: string;
  resolution: string;
  status: 'uploading' | 'completed' | 'failed';
  uploadingStatus?: string;
  generatedImages?: string[];
  createdAt: number;
  // 生成时的上下文信息
  context: {
    activeType: string;
    selectedFeature: string;
    selectedBusiness: string;
    isSmartPrompt: boolean;
    prompt: string;
  };
  // 添加图片元数据，减少存储空间
  imageMetadata?: {
    count: number;
    sizes: number[]; // 图片大小（字节）
    types: string[]; // 图片类型
  };
  // 开发工具相关字段
  taskId?: string; // ComfyUI任务ID
  apiFilePath?: string; // 使用的API JSON文件路径
  workflowName?: string; // 工作流名称
}

class HistoryManager {
  private readonly STORAGE_KEY = 'yunjian_historyList';

  // 获取历史记录列表
  getHistoryList(): GenerationHistoryItem[] {
    try {
      const stored = localStorage.getItem(this.STORAGE_KEY);
      if (!stored) return [];
      
      const historyList = JSON.parse(stored);
      
      // 处理向后兼容性：为没有 lightccImageUrls 字段的旧记录添加该字段
      return historyList.map((item: any) => {
        if (!item.lightccImageUrls) {
          // 如果旧记录没有 lightccImageUrls 字段，使用 imageUrls 作为默认值
          item.lightccImageUrls = item.imageUrls || [];
        }
        return item as GenerationHistoryItem;
      });
    } catch (error) {
      console.error('获取历史记录失败:', error);
      return [];
    }
  }

  // 检查存储空间
  private checkStorageQuota(): { available: boolean; used: number; total: number } {
    try {
      // 估算当前使用的存储空间
      const currentData = localStorage.getItem(this.STORAGE_KEY);
      const used = currentData ? new Blob([currentData]).size : 0;
      
      // 浏览器通常限制在5-10MB，我们保守估计5MB
      const total = 5 * 1024 * 1024; // 5MB
      
      return {
        available: used < total * 0.6, // 使用60%作为安全阈值，更保守
        used,
        total
      };
    } catch (error) {
      console.error('检查存储空间失败:', error);
      return { available: false, used: 0, total: 0 };
    }
  }

  // 优化图片数据以减少存储空间
  private async optimizeImageData(imageUrls: string[], lightccImageUrls: string[]): Promise<{ urls: string[]; lightccUrls: string[]; metadata: any }> {
    const optimizedUrls: string[] = [];
    const optimizedLightccUrls: string[] = [];
    const metadata = {
      count: imageUrls.length,
      sizes: [] as number[],
      types: [] as string[]
    };

    // 处理本地图片URL（用于显示）
    for (const url of imageUrls) {
      if (url && url.startsWith('data:')) {
        // 对于base64图片，直接保存
        optimizedUrls.push(url);
        metadata.sizes.push(url.length);
        metadata.types.push('base64');
      } else if (url && url.startsWith('blob:')) {
        // 对于blob URL，转换为base64
        try {
          const base64Url = await this.convertBlobToBase64(url);
          optimizedUrls.push(base64Url);
          metadata.sizes.push(base64Url.length);
          metadata.types.push('base64');
        } catch (error) {
          console.error('转换blob URL失败:', error);
          // 如果转换失败，使用占位符
          const placeholder = `data:image/placeholder;base64,${btoa('conversion-failed')}`;
          optimizedUrls.push(placeholder);
          metadata.sizes.push(0);
          metadata.types.push('placeholder');
        }
      } else {
        // 对于其他URL，直接保存
        optimizedUrls.push(url);
        metadata.sizes.push(0);
        metadata.types.push('url');
      }
    }

    // 处理LightCC图片URL（用于API调用）
    lightccImageUrls.forEach(url => {
      optimizedLightccUrls.push(url);
    });

    return { urls: optimizedUrls, lightccUrls: optimizedLightccUrls, metadata };
  }

  // 将blob URL转换为base64
  private async convertBlobToBase64(blobUrl: string): Promise<string> {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'anonymous';
      
      img.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        if (!ctx) {
          reject(new Error('无法获取canvas上下文'));
          return;
        }
        
        canvas.width = img.width;
        canvas.height = img.height;
        
        ctx.drawImage(img, 0, 0);
        
        try {
          const base64 = canvas.toDataURL('image/png', 0.8); // 使用0.8质量压缩
          resolve(base64);
        } catch (error) {
          reject(error);
        }
      };
      
      img.onerror = () => {
        reject(new Error('图片加载失败'));
      };
      
      img.src = blobUrl;
    });
  }

  // 保存历史记录列表
  private saveHistoryList(historyList: GenerationHistoryItem[]): void {
    try {
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(historyList));
    } catch (error) {
      console.error('保存历史记录失败:', error);
      // 如果存储空间不足，删除最旧的一条记录
      if (error instanceof Error && error.name === 'QuotaExceededError') {
        console.warn('存储空间不足，删除最旧的记录...');
        // 删除最旧的一条记录（数组最后一个）
        const cleanedList = historyList.slice(0, -1);
        try {
          localStorage.setItem(this.STORAGE_KEY, JSON.stringify(cleanedList));
          console.log('删除最旧记录后保存成功');
        } catch (retryError) {
          console.error('删除记录后仍然无法保存，清空所有数据:', retryError);
          localStorage.removeItem(this.STORAGE_KEY);
        }
      }
    }
  }

  // 添加新的历史记录
  async addHistoryItem(item: Omit<GenerationHistoryItem, 'id' | 'createdAt'>): Promise<string> {
    const historyList = this.getHistoryList();
    
    // 优化图片数据以减少存储空间
    const { urls: optimizedUrls, lightccUrls: optimizedLightccUrls, metadata } = await this.optimizeImageData(item.imageUrls, item.lightccImageUrls || []);
    
    const newItem: GenerationHistoryItem = {
      ...item,
      imageUrls: optimizedUrls,
      lightccImageUrls: optimizedLightccUrls,
      imageMetadata: metadata,
      id: this.generateId(),
      createdAt: Date.now()
    };
    
    historyList.unshift(newItem); // 添加到开头
    
    // 限制历史记录数量（保留最近20条，大幅减少存储压力）
    if (historyList.length > 20) {
      historyList.splice(20);
    }
    
    this.saveHistoryList(historyList);
    return newItem.id;
  }

  // 更新历史记录
  updateHistoryItem(id: string, updates: Partial<GenerationHistoryItem>): boolean {
    const historyList = this.getHistoryList();
    const index = historyList.findIndex(item => item.id === id);
    
    if (index !== -1) {
      historyList[index] = { ...historyList[index], ...updates };
      this.saveHistoryList(historyList);
      return true;
    }
    
    return false;
  }

  // 更新任务ID和API文件路径（开发工具专用）
  updateTaskInfo(id: string, taskId: string, apiFilePath: string, workflowName: string): boolean {
    return this.updateHistoryItem(id, {
      taskId,
      apiFilePath,
      workflowName
    });
  }

  // 根据任务ID查找历史记录（开发工具专用）
  findByTaskId(taskId: string): GenerationHistoryItem | null {
    const historyList = this.getHistoryList();
    return historyList.find(item => item.taskId === taskId) || null;
  }

  // 获取所有任务ID和API文件路径的映射（开发工具专用）
  getTaskApiMapping(): Array<{ taskId: string; apiFilePath: string; workflowName: string; date: string }> {
    const historyList = this.getHistoryList();
    return historyList
      .filter(item => item.taskId && item.apiFilePath)
      .map(item => ({
        taskId: item.taskId!,
        apiFilePath: item.apiFilePath!,
        workflowName: item.workflowName || '未知',
        date: item.date
      }))
      .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()); // 按时间倒序
  }

  // 删除历史记录
  deleteHistoryItem(id: string): boolean {
    const historyList = this.getHistoryList();
    const filteredList = historyList.filter(item => item.id !== id);
    
    if (filteredList.length !== historyList.length) {
      this.saveHistoryList(filteredList);
      return true;
    }
    
    return false;
  }

  // 清空历史记录
  clearHistory(): void {
    localStorage.removeItem(this.STORAGE_KEY);
  }

  // 清理存储空间（保留最近N条记录）
  cleanupStorage(keepCount: number = 20): void {
    const historyList = this.getHistoryList();
    if (historyList.length > keepCount) {
      const cleanedList = historyList.slice(0, keepCount);
      this.saveHistoryList(cleanedList);
      console.log(`清理存储空间，保留最近${keepCount}条记录`);
    }
  }

  // 获取存储空间使用情况
  getStorageInfo(): { used: number; total: number; percentage: number; itemCount: number } {
    const quota = this.checkStorageQuota();
    const historyList = this.getHistoryList();
    
    return {
      used: quota.used,
      total: quota.total,
      percentage: Math.round((quota.used / quota.total) * 100),
      itemCount: historyList.length
    };
  }

  // 根据功能类型获取format
  getFormatByFeatureType(activeType: string, selectedFeature: string): string {
    switch (activeType) {
      case 'image':
        return '图片生成';
      case 'video':
        return '视频生成';
      case 'digital':
        return '高清放大';
      case 'action':
        return selectedFeature === '草图（白模生图）' ? '草图生图' : '风格参考';
      default:
        return '图片生成';
    }
  }

  // 根据图片格式获取resolution
  getResolutionByImageFormat(imageUrls: string[]): string {
    if (!imageUrls || imageUrls.length === 0) return '2K';
    
    // 使用第一张图片来判断格式
    const imageUrl = imageUrls[0];
    const url = imageUrl.toLowerCase();
    if (url.includes('.png') || url.includes('png')) {
      return 'PNG';
    } else if (url.includes('.jpg') || url.includes('.jpeg') || url.includes('jpg') || url.includes('jpeg')) {
      return 'JPG';
    } else if (url.includes('.webp') || url.includes('webp')) {
      return 'WEBP';
    } else {
      return '2K'; // 默认
    }
  }

  // 根据业态类型获取aspectRatio
  getAspectRatioByBusiness(business: string): string {
    switch (business) {
      case '瑜伽':
        return '瑜伽';
      case 'SPA':
        return 'SPA';
      case '台球':
        return '台球';
      case '健身房':
        return '健身房';
      default:
        return '其他';
    }
  }

  // 生成唯一ID
  private generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  }

  // 创建新的历史记录项（用于任务开始时）
  async createHistoryItem(
    imageUrls: string[], // 本地图片URL（用于显示）
    lightccImageUrls: string[], // LightCC图片URL（用于API调用）
    context: {
      activeType: string;
      selectedFeature: string;
      selectedBusiness: string;
      isSmartPrompt: boolean;
      prompt: string;
    }
  ): Promise<string> {
    const format = this.getFormatByFeatureType(context.activeType, context.selectedFeature);
    const resolution = this.getResolutionByImageFormat(imageUrls);
    
    // 优先显示功能选择，如果没有功能选择则显示业态选择
    let aspectRatio: string;
    
    // 特殊处理：通过activeType标识的功能
    if (context.activeType === 'migration') {
      aspectRatio = '图像迁移';
    } else if (context.activeType === 'digital') {
      aspectRatio = '高清放大';
    } else if (context.activeType === 'video') {
      aspectRatio = '视频生成';
    }
    // 其他功能通过selectedFeature标识
    else if (context.selectedFeature && context.selectedFeature !== '展开功能') {
      aspectRatio = context.selectedFeature;
    } 
    // 默认显示业态选择
    else {
      aspectRatio = this.getAspectRatioByBusiness(context.selectedBusiness);
    }

    return await this.addHistoryItem({
      date: new Date().toISOString(),
      imageUrls,
      lightccImageUrls,
      format,
      aspectRatio,
      resolution,
      status: 'uploading',
      uploadingStatus: '正在生成',
      context
    });
  }
}

// 导出单例实例
export const historyManager = new HistoryManager();
